package cn.leven.web.session;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 *  输出流
*/
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
    protected void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException {
        int w = 100,h=50;

        BufferedImage img = new BufferedImage(w,h,BufferedImage.TYPE_INT_BGR); //创建图片
        // 美化图片
        Graphics g = img.getGraphics();
        g.setColor(Color.PINK);
        g.fillRect(0,0,w,h);
        g.setColor(Color.BLUE);
        g.drawRect(0,0,w-1,h-1);
        String str = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
        Random r = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i =0;i<4;i++){
            int index = r.nextInt(str.length());
            char ch = str.charAt(index);
            stringBuilder.append(ch);
            g.drawString(ch+"",20*(i+1),30);
        }
        String checkCodeSession = stringBuilder.toString();
        req.getSession().setAttribute("checkCodeSession",checkCodeSession);

        g.setColor(Color.GREEN);
        for (int i = 0 ;i<10;i++){
            int x1 = r.nextInt(w);
            int x2 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int y2 = r.nextInt(h);
            g.drawLine(x1,x2,y1,y2);
        }
        ImageIO.write(img, "jpg",res.getOutputStream()); // 返回图片

//        pw.write("<h1>hello response</h1><p>你好</p>");
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        this.doPost(req,res);
    }
}
